// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const users = db.collection('users')
  const openid = wxContext.OPENID

  // 查询用户是否已存在
  const userRes = await users.where({ _openid: openid }).get()
  if (userRes.data.length === 0) {
    // 新用户，初始化档案
    await users.add({
      data: {
        _openid: openid,
        nickname: event.nickname || '',
        avatar: event.avatar || '',
        register_time: new Date(),
        last_active: new Date(),
        level: 1,
        points: 0
      }
    })
  } else {
    // 老用户，更新活跃时间
    await users.where({ _openid: openid }).update({
      data: { last_active: new Date() }
    })
  }
  return {
    openid,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
} 